# -*- coding: utf-8 -*-
import re
from .infrastructure import Record
from multiprocessing.pool import ThreadPool as Pool
from multiprocessing import cpu_count
from functools import partial


class CPCATransformer:

    # 可以传入用户自定义区县map，因为原始数据区县map有很多key重复
    def __init__(self, u_map={}):
        self.umap = u_map
        self.cpuCount = cpu_count()
        self.data = ["江苏南京市建邺区友谊街38号9幢一单元103室", "江苏南京市建邺区友谊街38号4幢三单元1411室"]

    def transform(self, data, index=[], cut=True, lookahead=8):
        from .infrastructure import SuperMap
        pool = Pool()
        record = Record()

        para = partial(record.run, self.umap, cut, lookahead)
        poolRet = pool.map_async(para, self.data)
        ret = poolRet.get(timeout=3)
        SuperMap.rep_area_set = set()
        import pandas as pd
        if isinstance(data, pd.Series):
            data = data.astype(str)

        lines = []
        for line in data:
            lines.append(self.__del_data(line))


        para = partial(record.run, self.umap, cut, lookahead)
        poolRet = pool.map_async(para, lines)
        ret = poolRet.get(timeout=60)
        # pool.map(para, lines)

        pool.close()
        pool.join()
        return ret

    # 数据过滤
    def __del_data(self, line):

        line = re.sub(r'（\S+）', "", line)
        line = re.sub(r'\(\S+\)', "", line)
        line = re.sub(r'\[\S+\]', "", line)
        line = re.sub(r'[\[\]\(\)（）{}~]', "", line)
        return line
